//
//  LYVideoFullScreen.m
//  LYLiveApp
//
//  Created by QD on 16/8/30.
//  Copyright © 2016年 览益信息科技. All rights reserved.
//

#import "LYVideoFullScreen.h"
#import "LYVideoNoDataView.h"
#import "LYUMShareManager.h"
#import "LYUtil.h"
#import "LYVedioLiveController.h"
#import "LYCommentModel.h"
#import "UIView+Frame.h"
#import "LYFuDaiView.h"
#import "LYLoginNewController.h"

static const NSTimeInterval         kStatementTotalTime           = 5;
static const NSTimeInterval         kStatementIntervalTime        = 1.0f;

@interface LYVideoFullScreen ()<LYInputViewDelegate>

@property (strong, nonatomic) UIControl *controlView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *setViewLeading;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *shareViewLeading;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topViewTopSpace;   // 15
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomActionViewWidth;
@property (weak, nonatomic) IBOutlet UIButton *refressBtn;
@property (weak, nonatomic) IBOutlet UISlider *lightSlider;
@property (weak, nonatomic) IBOutlet UISlider *voiceSlider;
@property (weak, nonatomic) IBOutlet UIView *noDataView;
@property (weak, nonatomic) IBOutlet UIView *setView;
@property (weak, nonatomic) IBOutlet UIView *shareView;
@property (weak, nonatomic) IBOutlet UIView *lockView;
@property (weak, nonatomic) IBOutlet UIView *commentView;
@property (weak, nonatomic) IBOutlet UIView *likeView;
@property (weak, nonatomic) IBOutlet UIButton *highClearBtn;
@property (weak, nonatomic) IBOutlet UIButton *maxClearBth;
@property (weak, nonatomic) IBOutlet UIButton *normalClearBth;
@property (weak, nonatomic) IBOutlet UIButton *originClearBtn;
@property (weak, nonatomic) IBOutlet UIButton *commentBth;
@property (assign, nonatomic) BOOL   isShowRoundView;
@property (assign, nonatomic) BOOL   isLocked;
@property (strong, nonatomic) NSTimer *clickTimer;
@property (strong, nonatomic) UITapGestureRecognizer *showTap;
@property (strong, nonatomic) UIPanGestureRecognizer *panGesture;
@property (weak, nonatomic) IBOutlet UILabel *shareViewTitleLab;
@property (weak, nonatomic) IBOutlet UILabel *wechatFriendLab;
@property (weak, nonatomic) IBOutlet UILabel *wechatLab;
@property (weak, nonatomic) IBOutlet UILabel *qqZoneLab;
@property (weak, nonatomic) IBOutlet UILabel *sinaLab;
@property (weak, nonatomic) IBOutlet UILabel *qqLab;
@property (weak, nonatomic) IBOutlet UILabel *setViewTitleLab;
@property (weak, nonatomic) IBOutlet UIView *talkView;
@property (weak, nonatomic) IBOutlet UIView *audioView;
@property (weak, nonatomic) IBOutlet UIView *bottomActionView;
@property (strong, nonatomic) UIView *inputBg;
@property (nonatomic,strong) NSNumber *toChatId;
@property (weak, nonatomic) IBOutlet UIButton *changeScreenBtn;
@property (weak, nonatomic) IBOutlet UIButton *likeButton;
@property (weak, nonatomic) IBOutlet UILabel *likeNumLab;
@property (weak, nonatomic) IBOutlet UIButton *audioChangeBtn;
@property (weak, nonatomic) IBOutlet UIButton *definiBtn;
@property (weak, nonatomic) IBOutlet UIView *definiView;
@property (weak, nonatomic) IBOutlet UIView *definiImgView;
@property(nonatomic,assign) NSInteger stateMentCountTime;
@property(nonatomic,strong) NSTimer *stateMentTimer;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *changeScreenBtnTrailing;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *commentViewTrailing;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *likeViewTrailing;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lockViewTrailing;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *setBtnTrailing;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *talkViewLeading;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *talkViewTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomActionViewLeading;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *definiviewHeight;
@property (weak, nonatomic) IBOutlet UIImageView *bottomImageView;


@end

static const CGFloat        kShareViewWidth             = 214.0f  ;
static const CGFloat        kSetViewWidth               = 230.0f  ;
static const NSTimeInterval kAnimationTime              = 1.5f    ;
static const CGFloat        kAdjustRateValue            = 10.0f   ;

@implementation LYVideoFullScreen

- (void)awakeFromNib {
   
    [super awakeFromNib];
    [self _prepareView];
    [self _addFullScreenCommentView];
    [self _addNotification];
}

#pragma mark - notification events
- (void)keyboardWillShow:(NSNotification *)notification {
    WS(weakSelf)
    NSDictionary* info = [notification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    [UIView animateWithDuration:[info[UIKeyboardAnimationDurationUserInfoKey] doubleValue]
                          delay:0
                        options:([info[UIKeyboardAnimationCurveUserInfoKey] integerValue]<<16)
                     animations:^{
                         [weakSelf.fullScreenInputView mas_updateConstraints:^(MASConstraintMaker *make) {
                             make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 53));
                            // make.right.mas_equalTo(0);
                             make.bottom.mas_equalTo(- kbSize.height);
                             
                         }];
                         weakSelf.fullScreenInputView.inputView.width = SCREEN_WIDTH - 118;
                         weakSelf.fullScreenInputView.sendBtn.x = SCREEN_WIDTH - 62;
                         weakSelf.inputBg.hidden = NO;
                         [weakSelf bringSubviewToFront:weakSelf.inputBg];
                         [weakSelf layoutIfNeeded];
                     }
                     completion:^(BOOL finished){
                     }];
}


- (void)keyboardWillHidden:(NSNotification *)notification {
    WS(weakSelf)
    NSDictionary* info = [notification userInfo];
    [UIView animateWithDuration:[info[UIKeyboardAnimationDurationUserInfoKey] doubleValue]
                          delay:0
                        options:([info[UIKeyboardAnimationCurveUserInfoKey] integerValue]<<16)
                     animations:^{
                         [weakSelf.fullScreenInputView mas_updateConstraints:^(MASConstraintMaker *make) {
                             make.bottom.mas_equalTo(53);
                             make.height.mas_equalTo(self.fullScreenInputView.bounds.size.height);
                         }];
                         weakSelf.fullScreenInputView.placeHolder = @"参与讨论";
                         weakSelf.inputBg.hidden = YES;
                         [weakSelf layoutIfNeeded];
                     }
                     completion:nil];
}

- (void)setScreenType:(FullScreenType)screenType {
    _screenType = screenType;
    self.titleLab.text = [LYLocalData sharedInstance].roomInfo.name;
    if (screenType == FullScreenTypeShow) {
        self.isShowRoundView = YES;
        [self _showViewAction];
        self.noVideoView.userInteractionEnabled = YES;
        [self.noVideoView addGestureRecognizer:_showTwoTap];
    } else if (screenType == FullScreenTypeFail) {
        self.isNoVideo = YES; 
    }
    if (self.isAudio) {
        self.audioView.hidden = NO;
        self.audioChangeBtn.selected = YES;
        self.highClearBtn.selected   = NO;
        self.maxClearBth.selected    = NO;
        self.normalClearBth.selected = NO;
        self.originClearBtn.selected = NO;
    }
    else {
        self.audioView.hidden = YES;
        self.audioChangeBtn.selected = NO;
    }
}

- (void)setDefinitionArray:(NSArray *)definitionArray {
    
    self.originClearBtn.selected = NO;

    if (self.definition == VHallMovieDefinitionHD) {
        [self.definiBtn setTitle:@"高清" forState:UIControlStateNormal];
    } else if (self.definition == VHallMovieDefinitionSD) {
        [self.definiBtn setTitle:@"标清" forState:UIControlStateNormal];
    } else if (self.definition == VHallMovieDefinitionUHD) {
        [self.definiBtn setTitle:@"超清" forState:UIControlStateNormal];
    } else if (self.definition == VHallMovieDefinitionOrigin) {
        [self.definiBtn setTitle:@"原画" forState:UIControlStateNormal];
        self.originClearBtn.selected = YES;
    }
    self.maxClearBth.selected = self.definition == VHallMovieDefinitionUHD ? YES : NO;
    if (!definitionArray.count) return;
    self.maxClearBth.enabled    = NO;
    self.highClearBtn.enabled   = NO;
    self.normalClearBth.enabled = NO;
    self.originClearBtn.enabled = NO;
    self.maxClearBth.enabled = [definitionArray containsObject:@1] ? YES : NO;
    self.highClearBtn.enabled = [definitionArray containsObject:@2] ? YES : NO;
    self.normalClearBth.enabled = [definitionArray containsObject:@3] ? YES : NO;
    self.originClearBtn.enabled = [definitionArray containsObject:@0] ? YES : NO;
    self.maxClearBth.selected = self.definition == VHallMovieDefinitionUHD ? YES : NO;
    self.highClearBtn.selected = self.definition == VHallMovieDefinitionHD  ? YES :NO;
    self.normalClearBth.selected = self.definition == VHallMovieDefinitionSD ? YES : NO;
//    self.originBtn.selected = self.definition = VHallMovieDefinitionOrigin ? YES : NO;
}

- (void)_prepareView {
   
    self.definiImgView.hidden = YES;
    [self.voiceSlider setThumbImage:[UIImage imageNamed:@"video_silder"] forState:UIControlStateNormal];
    self.voiceSlider.value = [VHallMoviePlayer getSysVolumeSize];
    [self.lightSlider setThumbImage:[UIImage imageNamed:@"video_silder"] forState:UIControlStateNormal];
    self.lightSlider.value = [UIScreen mainScreen].brightness;
    [self.voiceSlider addTarget:self action:@selector(voiceChange:) forControlEvents:UIControlEventValueChanged];
    [self.lightSlider addTarget:self action:@selector(lightChange:) forControlEvents:UIControlEventValueChanged];
    self.refressBtn.layer.cornerRadius = 4.0f;
    self.refressBtn.layer.masksToBounds = YES;
    self.refressBtn.layer.borderWidth = 0.5f;
    self.refressBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    _showTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_showViewAction)];
    self.userInteractionEnabled = YES;
    [self addGestureRecognizer:_showTap];
    _panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(_handleSwipe:)];
    [self addGestureRecognizer:_panGesture];
    _showTwoTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_showViewAction)];
    if (IS_IPHONE_6 || IS_IPHONE_6P) {
        self.maxClearBth.titleLabel.font      = [UIFont systemFontOfSize:16.0f];
        self.highClearBtn.titleLabel.font     = [UIFont systemFontOfSize:16.0f];
        self.normalClearBth.titleLabel.font   = [UIFont systemFontOfSize:16.0f];
        self.originClearBtn.titleLabel.font        = [UIFont systemFontOfSize:16.0f];
        self.titleLab.font                    = [UIFont systemFontOfSize:15.0f];
        self.shareViewTitleLab.font           = [UIFont systemFontOfSize:14.0f];
        self.setViewTitleLab.font             = [UIFont systemFontOfSize:14.0f];
        self.wechatFriendLab.font             = [UIFont systemFontOfSize:11.0f];
        self.wechatLab.font                   = [UIFont systemFontOfSize:11.0f];
        self.qqLab.font                       = [UIFont systemFontOfSize:11.0f];
        self.qqZoneLab.font                   = [UIFont systemFontOfSize:11.0f];
        self.sinaLab.font                     = [UIFont systemFontOfSize:11.0f];
    }    
    if (IS_IPHONE_4_OR_LESS) {     
        self.bottomActionViewWidth.constant = 225;
    } else if (IS_IPHONE_5)
        self.bottomActionViewWidth.constant = 290;
    if (IS_IPhoneX_All) {
        self.talkViewLeading.constant = 30;
        self.changeScreenBtnTrailing.constant = 35;
        self.commentViewTrailing.constant = 35;
        self.likeViewTrailing.constant = 35;
        self.commentViewTrailing.constant = 35;
        self.lockViewTrailing.constant = 25;
        self.setBtnTrailing.constant = 35;
        self.talkViewTop.constant = 0;
    }
}

- (void)_addNotification {

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(zanNumChange:) name:kWebSocketVideoZanNumChange object:nil];
}

- (void)stopRefreshCommentTimer {
    
    if (self.commentVC) {
        [self.commentVC stopRefreshCommentTimer];
    }
}

- (void)beginRefreshCommentTimer {
    
    if (self.commentVC) {
        [self.commentVC beginRefreshCommentTimer];
    }
}

- (void)_addFullScreenCommentView {
   
    self.commentVC = [[LYCommentController alloc] initWithNibName:@"LYCommentController" bundle:nil];
    self.commentVC.view.frame = CGRectMake(12, 0, self.talkView.size.width - 30,self.talkView.height - 65);
  //  self.commentVC.commentTable.transform = CGAffineTransformMakeScale(1, -1);
    self.commentVC.commentTable.showsVerticalScrollIndicator = NO;
    [self.talkView addSubview:self.commentVC.view];
    self.commentVC.view.backgroundColor = [UIColor clearColor];
    self.talkView.backgroundColor = [UIColor clearColor];
    self.commentVC.isFullScrComment = YES;
    self.commentVC.commentTable.backgroundColor = [UIColor clearColor];
    [self.commentVC.commentTable reloadData];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(commentInputViewAction)];
    self.bottomActionView.userInteractionEnabled = YES;
    [self.bottomActionView addGestureRecognizer:tap];
    
    [self addSubview:self.fullScreenInputView];
    [self.fullScreenInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 53));
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(53);  
    }];
    
    [self addSubview:self.inputBg];
    [self.inputBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.bottom.equalTo(self.fullScreenInputView.mas_top).offset(0);
    }];
    [self insertSubview:self.fullScreenInputView aboveSubview:self.inputBg];
}

- (void)_handleSwipe:( UIPanGestureRecognizer *)panGesture {
    if (self.isLocked || !self.isShowRoundView) return;
    CGFloat beginBrightness = [UIScreen mainScreen].brightness;
    CGFloat beginVoice = [VHallMoviePlayer getSysVolumeSize];
    CGFloat offsetY = [panGesture translationInView:self].y;
    CGFloat locationX = [panGesture locationInView:self].x;
    
    if (locationX <= SCREEN_WIDTH / 2.0) {   //左边
        if (offsetY > 0.0) {  //下滑
            CGFloat newBrightness = beginBrightness - fabs(offsetY / SCREEN_HEIGHT)/kAdjustRateValue;
            if(newBrightness < 0.0)
            {
                newBrightness = 0.0;
            }
            [UIScreen mainScreen].brightness = newBrightness;

        } else if (offsetY < 0.0) {   //上滑
            CGFloat newBrightness = beginBrightness  + fabs(offsetY /SCREEN_HEIGHT)/kAdjustRateValue;
            if(newBrightness > 1.0)
            {
                newBrightness = 1.0;
            }
            [UIScreen mainScreen].brightness = newBrightness;
        }
    } else {  //右边
        
        if (offsetY > 0.0) {  //下滑
            CGFloat newVoice = beginVoice - fabs(offsetY / SCREEN_HEIGHT)/kAdjustRateValue;
            if(newVoice < 0.0)
            {
                newVoice = 0.0;
            }
            [VHallMoviePlayer setSysVolumeSize:newVoice];
        } else if (offsetY < 0.0) {   //上滑
            CGFloat newVoice = beginVoice  + fabs(offsetY /SCREEN_HEIGHT)/kAdjustRateValue;
            if(newVoice > 1.0)
            {
                newVoice = 1.0;
            }
            [VHallMoviePlayer setSysVolumeSize:newVoice];
        }
    }
}

#pragma mark ----- private method
- (void)_showViewAction {
    WS(weakSelf)
    if (!self.isShowRoundView) {
        if (self.isLocked) {
            weakSelf.lockView.alpha = 0;

        } else {
            weakSelf.lockView.alpha = 0;
            weakSelf.commentView.alpha = 0;
            weakSelf.likeView.alpha = 0;
            weakSelf.talkView.alpha = 0;
            weakSelf.audioChangeBtn.alpha = 0;
            weakSelf.definiView.alpha = 0;
            weakSelf.changeScreenBtn.alpha = 0;
            weakSelf.bottomImageView.alpha = 0;
            [UIView animateWithDuration:kAnimationTime animations:^{
                weakSelf.topViewTopSpace.constant    = -73;
                [[UIApplication sharedApplication] setStatusBarHidden:YES];
            } completion:^(BOOL finished) {
            }];
        }
    } else {
        if (self.isLocked) {
            weakSelf.lockView.alpha = 1;
        } else {
            weakSelf.lockView.alpha = 1;
            weakSelf.commentView.alpha = 1;
            weakSelf.likeView.alpha = 1;
            weakSelf.talkView.alpha = 1;
            weakSelf.audioChangeBtn.alpha = 1;
            weakSelf.definiView.alpha = 1;
            weakSelf.changeScreenBtn.alpha = 1;
            weakSelf.bottomImageView.alpha = 1;
            [UIView animateWithDuration:kAnimationTime animations:^{
                weakSelf.topViewTopSpace.constant    = 0;
                [[UIApplication sharedApplication] setStatusBarHidden:NO];
            } completion:^(BOOL finished) {
            }];
        }
    }
    self.isShowRoundView = !self.isShowRoundView;
}

- (void)hideTopView {
    WS(weakSelf)
    weakSelf.lockView.alpha = 0;
    weakSelf.commentView.alpha = 0;
    weakSelf.likeView.alpha = 0;
    weakSelf.audioChangeBtn.alpha = 0;
    weakSelf.definiView.alpha = 0;
    [UIView animateWithDuration:kAnimationTime animations:^{
        weakSelf.topViewTopSpace.constant     = -73;
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    } completion:^(BOOL finished) {
    }];
    self.isShowRoundView = YES;
}

- (void)_borderStyleButton:(UIButton *)button state:(NSInteger)state {
    button.layer.cornerRadius = 3.0f;
    button.layer.borderWidth = 0.8f;
    if (state == 1) {
        button.layer.borderColor = [UIColor colorWithHexString:@"d94b41"].CGColor;
    } else {
        button.layer.borderColor = [UIColor whiteColor].CGColor;
    }
}

- (void)_startStatementTimer {
    [self stopStatementTimer];
    if (nil == _stateMentTimer) {
        _stateMentTimer = [NSTimer scheduledTimerWithTimeInterval:kStatementIntervalTime
                                                           target:self
                                                         selector:@selector(_stateMentEnable)
                                                         userInfo:nil
                                                          repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:self.stateMentTimer forMode:NSRunLoopCommonModes];
    } else {
        if (fabs([self.stateMentTimer.fireDate timeIntervalSinceNow]) < kStatementIntervalTime)
            [self.stateMentTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:kStatementIntervalTime]];
    }
}

- (void)stopStatementTimer {
    
    if (self.stateMentTimer) {
        [self.stateMentTimer invalidate];
        self.stateMentTimer = nil;
    }
}

- (void)_stateMentEnable {
    
    if (self.stateMentCountTime < 0)         self.stateMentCountTime = 0;
    [self.fullScreenInputView.sendBtn setTitle:[NSString stringWithFormat:@"%lds",(long)self.stateMentCountTime] forState:UIControlStateNormal];
    self.stateMentCountTime --;
    if (self.stateMentCountTime <= 0) {
        [self.fullScreenInputView.sendBtn setTitle:@"发送" forState:UIControlStateNormal];
        [self stopStatementTimer];
        self.fullScreenInputView.sendBtn.enabled = YES;
        self.stateMentCountTime = 0;
    }
}


#pragma mark ----- event response

- (IBAction)definiChangeAction:(UIButton *)button {
    
//    if (!button.selected) {
//        self.definiviewHeight.constant = 141;
//        button.selected = YES;
//    } else {
//        self.definiviewHeight.constant = 23;
//        button.selected = NO;
//    }
    self.definiImgView.hidden = !self.definiImgView.hidden;
}

- (IBAction)audioVideoChange:(id)sender {
    
    if (self.audioChangeBtn.selected) {
        if (self.definitionblock) {
            self.definitionblock(VHallMovieDefinitionUHD);
            self.definition = VHallMovieDefinitionUHD;
            self.audioView.hidden = YES;
            [LYLocalData sharedInstance].isVideo = YES;
        }
    } else {
        if (self.definitionblock) {
            self.definitionblock(VHallMovieDefinitionAudio);
            self.definition = VHallMovieDefinitionAudio;
            self.audioView.hidden = NO;
            [LYLocalData sharedInstance].isVideo = NO;

        }
    }
    self.audioChangeBtn.selected = !self.audioChangeBtn.selected;
}

- (IBAction)changeScreenAction:(id)sender {
  
    if (self.backBlock) {
        self.backBlock();
    }
}

- (void)replayAction:(NSNotification *)notifycation {
    LYCommentModel *model = notifycation.userInfo[@"model"];
    self.toChatId = model.oid;
    [self.fullScreenInputView.inputView becomeFirstResponder];
    NSString *str = [NSString stringWithFormat:@"回复%@",model.show.user.nickname];
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:str];
    [attributedStr addAttribute:NSForegroundColorAttributeName
                          value:[UIColor blackColor]
                          range:NSMakeRange(2, model.show.user.nickname.length)];
    self.fullScreenInputView.placeHolderLabel.attributedText = attributedStr;
}

-(void)zanNumChange:(NSNotification *)notifycation {
    
    NSString *zanNumStr = notifycation.userInfo[@"zan_num"];
    self.likeNumLab.text = [NSString stringWithFormat:@"%@",zanNumStr];
}

-(void) touchBGView:(UITapGestureRecognizer *)ges {
    [self.fullScreenInputView.inputView resignFirstResponder];
}

- (void)commentInputViewAction {
    
    WS(weakSelf)
    if (![LYLocalData sharedInstance].isUserLogined) {
        [LYUtil showFailedHUD:@"还未登录,请先登录" AddedTo:MAIN_WINDOW interval:1.5];
        [LYLocalData sharedInstance].isFromVideoPageLogin = YES;
        !self.backBlock?:self.backBlock();
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [LYLoginNewController taskAfterLogin:^{
               
                [weakSelf.fullScreenInputView.inputView becomeFirstResponder];
                [LYLocalData sharedInstance].isFromVideoPageLogin = NO;

                [[SensorsAnalyticsSDK sharedInstance] track:@"SignUp"
                                             withProperties:@{
                                                              @"ly_register_succeed":@(YES),
                                                              @"ly_register_source":@"视频互动",
                                                              }];
            }];
        });
    } else {
        [weakSelf.fullScreenInputView.inputView becomeFirstResponder];
    }
}

- (void)voiceChange:(UISlider *)slider {
    if (self.voiceBlock) {
        self.voiceBlock(slider.value);
    }
}

- (void)lightChange:(UISlider *)slider {
    [[UIScreen mainScreen] setBrightness:slider.value];
}

- (IBAction)backAction:(id)sender {

    if (self.backBlock) {
        self.backBlock();
    }
}

- (IBAction)lockAction:(id)sender {
   WS(weakSelf)
    UIButton *button = (UIButton *)sender;
    button.selected = !button.selected;
    if (self.lockBlock) {
        self.lockBlock(button.selected);
    }
    if (button.selected) {
        self.isLocked = YES;
        weakSelf.commentView.alpha = 0;
        weakSelf.likeView.alpha = 0;
        weakSelf.lockView.alpha = 1;
        weakSelf.talkView.alpha = 0;
        weakSelf.audioChangeBtn.alpha = 0;
        weakSelf.definiView.alpha = 0;
        weakSelf.changeScreenBtn.alpha = 0;
        [UIView animateWithDuration:kAnimationTime animations:^{
            weakSelf.topViewTopSpace.constant     = -73;
            [[UIApplication sharedApplication] setStatusBarHidden:YES];
        } completion:^(BOOL finished) {
        }];
    } else {
        self.isLocked = NO;
        weakSelf.lockView.alpha = 1;
        weakSelf.commentView.alpha = 1;
        weakSelf.likeView.alpha = 1;
        weakSelf.talkView.alpha = 1;
        weakSelf.audioChangeBtn.alpha = 1;
        weakSelf.definiView.alpha = 1;
        weakSelf.changeScreenBtn.alpha = 1;
        [UIView animateWithDuration:kAnimationTime animations:^{
            weakSelf.topViewTopSpace.constant     = 0;
            [[UIApplication sharedApplication] setStatusBarHidden:NO];
        } completion:^(BOOL finished) {
        }];
    }
}


- (IBAction)shareAction:(id)sender {
    
    WS(weakSelf)
    if (self.isNoVideo)         return;
    [self addSubview:self.controlView];
    [self insertSubview:self.shareView aboveSubview:self.controlView];
    [UIView animateWithDuration:kAnimationTime animations:^{
        if (isIPhoneX) {
            weakSelf.shareViewLeading.constant = - 245;
        } else {
            weakSelf.shareViewLeading.constant = - kShareViewWidth;
        }
    } completion:^(BOOL finished) {
    }];
}

- (IBAction)setViewAction:(id)sender {
    
    WS(weakSelf)
    if (self.isNoVideo)         return;
    [self addSubview:self.controlView];
    [self insertSubview:self.setView aboveSubview:self.controlView];
    [UIView animateWithDuration:kAnimationTime animations:^{
        if (isIPhoneX) {
            weakSelf.setViewLeading.constant = - 260;
        } else {
            weakSelf.setViewLeading.constant = - kSetViewWidth;
        }
    } completion:^(BOOL finished) {
    }];
}

- (IBAction)commentAction:(id)sender {
    UIButton *commentBtn = (UIButton *)sender;
    commentBtn.selected = !commentBtn.selected;
    self.talkView.hidden = !self.talkView.hidden;
    self.commentVC.commentService.hasNewData = NO;
}

- (IBAction)likeAction:(id)sender {
 
    WS(weakSelf)
    UIButton *button = (UIButton *)sender;
    if (!button.selected) {
        NSString *url = [NSString stringWithFormat:@"%@/%@",LYSERVER,@"v1/room/like"];
        NSDictionary *paraDic = @{
                                  @"rid":@([LYLocalData sharedInstance].roomInfo.id.integerValue)
                                  };
        [[LYHTTPSessionManager sharedInstance] POST:url parameters:paraDic success:^(id response, NSURLSessionDataTask *task) {
            NSInteger code = [response[@"code"] integerValue];
            NSString *message = response[@"msg"];
            
            if (code == 200)
            {
                weakSelf.likeButton.selected  = YES;
                weakSelf.likeNumLab.text      = [NSString stringWithFormat:@"%ld",(long)_model.zan_num.integerValue + 1];
                weakSelf.model.zan_num = @(_model.zan_num.integerValue + 1);
                weakSelf.model.is_zan = @1;
                if (weakSelf.likeSuccessBlock) {
                    weakSelf.likeSuccessBlock(weakSelf.model);
                }
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    weakSelf.likeButton.selected  = NO;
                });
            }
            else
            {
                weakSelf.likeButton.selected  = NO;
                [LYUtil showLongTextFailedHUD:message AddedTo:MAIN_WINDOW interval:2];
            }
        } failure:^(NSError *error) {
            LYLog(@"error %@",[error localizedDescription]);
        }];
    }
}

- (IBAction)originClearAction:(id)sender {
    
    self.highClearBtn.selected = NO;
    self.maxClearBth.selected = NO;
    self.normalClearBth.selected = NO;
    self.originClearBtn.selected = YES;
    self.audioChangeBtn.selected = NO;
    self.audioView.hidden = YES;
    [self.definiBtn setTitle:@"原画" forState:UIControlStateNormal];
    self.definiImgView.hidden = YES;
    [self.controlView removeFromSuperview];
    if (self.definitionblock) {
        self.definitionblock(VHallMovieDefinitionOrigin);
    }
    self.definition = VHallMovieDefinitionOrigin;
    self.setViewLeading.constant = 0;

}

- (IBAction)hightClearAction:(id)sender {
    self.highClearBtn.selected = YES;
    self.maxClearBth.selected = NO;
    self.normalClearBth.selected = NO;
    self.originClearBtn.selected = NO;
    self.audioChangeBtn.selected = NO;
    self.audioView.hidden = YES;
    [self.definiBtn setTitle:@"高清" forState:UIControlStateNormal];
    self.definiImgView.hidden = YES;
    [self.controlView removeFromSuperview];
    if (self.definitionblock) {
        self.definitionblock(VHallMovieDefinitionHD);
    }
    self.definition = VHallMovieDefinitionHD;
    self.setViewLeading.constant = 0;
}

- (IBAction)maxClearAction:(id)sender {
    self.highClearBtn.selected = NO;
    self.maxClearBth.selected = YES;
    self.normalClearBth.selected = NO;
    self.originClearBtn.selected = NO;
    self.audioChangeBtn.selected = NO;
    self.audioView.hidden = YES;
    [self.definiBtn setTitle:@"超清" forState:UIControlStateNormal];
    self.definiImgView.hidden = YES;
    [self.controlView removeFromSuperview];
    if (self.definitionblock) {
        self.definitionblock(VHallMovieDefinitionUHD);
    }
    self.definition = VHallMovieDefinitionUHD;
    self.setViewLeading.constant = 0;
}

- (IBAction)normalClearAction:(id)sender {
    self.highClearBtn.selected = NO;
    self.maxClearBth.selected = NO;
    self.normalClearBth.selected = YES;
    self.originClearBtn.selected = NO;
    self.audioChangeBtn.selected = NO;
    self.audioView.hidden = YES;
    [self.definiBtn setTitle:@"标清" forState:UIControlStateNormal];
    self.definiImgView.hidden = YES;
    [self.controlView removeFromSuperview];
    if (self.definitionblock) {
        self.definitionblock(VHallMovieDefinitionSD);
    }
    self.definition = VHallMovieDefinitionSD;
    self.setViewLeading.constant = 0;
}

- (void)resetViewAction {
    WS(weakSelf)
    [UIView animateWithDuration:kAnimationTime animations:^{
        weakSelf.shareViewLeading.constant = 0;
        weakSelf.setViewLeading.constant   = 0;
    } completion:^(BOOL finished) {
        [_controlView removeFromSuperview];
    }];
}

- (IBAction)refreshAction:(id)sender {
    if (self.refreshBlock) {
        self.refreshBlock();
    }
}

- (UIViewController *)_getViewController {
    
    for (UIView *view = self; view; view = view.superview) {
        UIResponder *nextResponder = [view nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}


#pragma mark ----- LYInputViewDelegate
- (void)sendInputViewText:(NSString *)text {
    
    WS(weakSelf)
    if ([LYUtil isNilOrEmpty:text])  return;
    if (![self.fullScreenInputView.sendBtn.titleLabel.text isEqualToString:@"发送"]) return;

    [self.fullScreenInputView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(53);
        make.height.mas_equalTo(53);
    }];
    [self layoutIfNeeded];
    NSString *content = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (content.length > 200) {
        [LYUtil showFailedHUD:@"输入内容不能超过200字" AddedTo:self interval:2.0];
        return;
    }
    self.inputBg.hidden = YES;
    if (content.length) {
        [self.commentVC makeStatementWithId:self.toChatId content:content successBlock:^(BOOL success) {
            if (success) {
                self.toChatId = @0;
                [self.fullScreenInputView.inputView resignFirstResponder];
                weakSelf.stateMentCountTime = kStatementTotalTime;
                [self.fullScreenInputView.sendBtn setTitle:[NSString stringWithFormat:@"%lds",(long)self.stateMentCountTime] forState:UIControlStateNormal];
                [weakSelf _startStatementTimer];
                weakSelf.fullScreenInputView.sendBtn.enabled = NO;

            }
        }];
    }
}

- (void)textViewDidChange:(UITextView *)textView {
    WS(weakSelf)
    [self.fullScreenInputView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(weakSelf.fullScreenInputView.bounds.size.height);
    }];
    [self layoutIfNeeded];
}

- (BOOL)textViewBeginEditing:(UITextView *)textView {
    WS(weakSelf)
    [self.fullScreenInputView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(weakSelf.fullScreenInputView.bounds.size.height);
    }];
    return YES;
}


#pragma mark ----- shareAction
- (IBAction)wechatFriendAction:(id)sender {
   
    [self resetViewAction];
    LYVedioLiveController *viewController = nil;
    UIViewController *VC = [self _getViewController];
    if ([VC isKindOfClass:[NSClassFromString(@"LYVedioLiveController") class]]) {
        viewController = (LYVedioLiveController *)VC;
    }
    
    LYShareManagerModel *shareModel = [LYShareManagerModel modelWithTitle:kShareVideoTitle content:kShareContent imageUrl:kShareImgUrl url:kShareVideoUrl];
    [LYUMShareManager UMShareTitle:shareModel.shareTitle shareContent:shareModel.shareContent shareImage:shareModel.shareImageUrl shareType:LYShareWeixiTimeline shareUrl:shareModel.shareUrl presentedController:viewController completBlock:^(id result, NSError *error) {
        
        if (error == nil) {
            [[NSNotificationCenter defaultCenter] postNotificationName:kFullScreenShareDoneNotification object:@"5"];
        }
    }];
}

- (IBAction)wechatAction:(id)sender {
   
    [self resetViewAction];
    LYVedioLiveController *viewController = nil;
    UIViewController *VC = [self _getViewController];
    if ([VC isKindOfClass:[NSClassFromString(@"LYVedioLiveController") class]]) {
        viewController = (LYVedioLiveController *)VC;
    }
    
    LYShareManagerModel *shareModel = [LYShareManagerModel modelWithTitle:kShareVideoTitle content:kShareContent imageUrl:kShareImgUrl url:kShareVideoUrl];
    [LYUMShareManager UMShareTitle:shareModel.shareTitle shareContent:shareModel.shareContent shareImage:shareModel.shareImageUrl shareType:LYShareWeixiSession shareUrl:shareModel.shareUrl presentedController:viewController completBlock:^(id result, NSError *error) {
        if (error == nil) {
            [[NSNotificationCenter defaultCenter] postNotificationName:kFullScreenShareDoneNotification object:@"2"];
        }
    }];
}

- (IBAction)qqZone:(id)sender {
   
    if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]) {
        [LYUtil showFailedHUD:@"请安装QQ客户端" AddedTo:self interval:2.0];
        return;
    }

    [self resetViewAction];
    LYVedioLiveController *viewController = nil;
    UIViewController *VC = [self _getViewController];
    if ([VC isKindOfClass:[NSClassFromString(@"LYVedioLiveController") class]]) {
        viewController = (LYVedioLiveController *)VC;
    }
    LYShareManagerModel *shareModel = [LYShareManagerModel modelWithTitle:kShareVideoTitle content:kShareContent imageUrl:kShareImgUrl url:kShareVideoUrl];
    [LYUMShareManager UMShareTitle:shareModel.shareTitle shareContent:shareModel.shareContent shareImage:shareModel.shareImageUrl shareType:LYShareQQSpace shareUrl:shareModel.shareUrl presentedController:viewController completBlock:^(id result, NSError *error) {
        
        if (error == nil) {
            [[NSNotificationCenter defaultCenter] postNotificationName:kFullScreenShareDoneNotification object:@"4"];
        }
    }];
}

- (IBAction)sinaAction:(id)sender {
    
    if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"sinaweibo://"]]) {
        [LYUtil showFailedHUD:@"请安装新浪客户端" AddedTo:self interval:2.0];
        return;
    }
    
    [self resetViewAction];
    LYVedioLiveController *viewController = nil;
    UIViewController *VC = [self _getViewController];
    if ([VC isKindOfClass:[NSClassFromString(@"LYVedioLiveController") class]]) {
        viewController = (LYVedioLiveController *)VC;
    }
    
    LYShareManagerModel *shareModel = [LYShareManagerModel modelWithTitle:kShareVideoTitle content:kShareContent imageUrl:kShareImgUrl url:kShareVideoUrl];
    [LYUMShareManager UMShareTitle:shareModel.shareTitle shareContent:shareModel.shareContent shareImage:shareModel.shareImageUrl shareType:LYSinaWeibo shareUrl:shareModel.shareUrl presentedController:viewController completBlock:^(id result, NSError *error) {
        
        if (error == nil) {
            [[NSNotificationCenter defaultCenter] postNotificationName:kFullScreenShareDoneNotification object:@"3"];
        }
    }];
}

- (IBAction)qqAction:(id)sender {
    
    if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]) {
        [LYUtil showFailedHUD:@"请安装QQ客户端" AddedTo:self interval:2.0];
        return;
    }

    [self resetViewAction];
    LYVedioLiveController *viewController = nil;
    UIViewController *VC = [self _getViewController];
    if ([VC isKindOfClass:[NSClassFromString(@"LYVedioLiveController") class]]) {
        viewController = (LYVedioLiveController *)VC;
    }
    
    LYShareManagerModel *shareModel = [LYShareManagerModel modelWithTitle:kShareVideoTitle content:kShareContent imageUrl:kShareImgUrl url:kShareVideoUrl];
    [LYUMShareManager UMShareTitle:shareModel.shareTitle shareContent:shareModel.shareContent shareImage:shareModel.shareImageUrl shareType:LYShareQQ shareUrl:shareModel.shareUrl presentedController:viewController completBlock:^(id result, NSError *error) {
        
        if (error == nil) {
            [[NSNotificationCenter defaultCenter] postNotificationName:kFullScreenShareDoneNotification object:@"1"];
        }
    }];
}

- (void)setModel:(LYIntroduceModel *)model {
   
    _model = model;
    self.likeNumLab.text = [NSString stringWithFormat:@"%ld",(long)model.zan_num.integerValue];
}

+ (instancetype)viewWithXib
{
    LYVideoFullScreen *view = [[[UINib nibWithNibName:@"LYVideoFullScreen" bundle:nil] instantiateWithOwner:self options:nil] lastObject];
    return view;
}

- (UIControl *)controlView {

    if (nil == _controlView) {
        _controlView = [[UIControl alloc] init];
        _controlView.frame = self.frame;
        _controlView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resetViewAction)];
        [_controlView addGestureRecognizer:tap];
        _controlView.backgroundColor = [UIColor clearColor];
    }
    return _controlView;
}

- (LYInputView *)fullScreenInputView
{
    if (nil == _fullScreenInputView) {
        _fullScreenInputView = [[LYInputView alloc] initWithStyle:DefaultInputBarStyle];
        _fullScreenInputView.delegate = self;
        _fullScreenInputView.alpha = 1;
        _fullScreenInputView.backgroundColor = [UIColor colorWithHexString:@"#d8d9db"];
        _fullScreenInputView.keyboard.showAddBtn = NO;
        [_fullScreenInputView.keyboard addBtnClicked:^{  }];
        _fullScreenInputView.placeHolder = @"互动";
    }
    return _fullScreenInputView;
}

-(UIView *)inputBg {
    
    if (nil == _inputBg) {
        _inputBg = [[UIView alloc] init];
        _inputBg.backgroundColor = RGBA(0, 0, 0, 0.3);
        _inputBg.hidden = YES;
        UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchBGView:)];
        [_inputBg addGestureRecognizer:tapGes];
    }
    return _inputBg;
}


@end
